<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .container {
      width: 800px;
      margin: 50px;
    }

    #box {
      width: 500px;
      height: 500px;
      border: solid 1px red;
      position: relative;
      margin-top: 10px;
    }

    #move {
      width: 100px;
      height: 100px;
      background-color: blueviolet;
      position: absolute;
    }
  </style>
</head>

<body>
  <div class="container">
    <form action="" method="post">
      请输入移动距离：<input type="text" id="distance"><br>
      <button id="button1" type="button">进行移动</button>
      <button id="left-button">向左走</button>
      <button id="right-button">向右走</button>
    </form>
  </div>
  <div id="box">
    <div id="move"></div>
  </div>
</body>
<script>
  var button1 = document.getElementById('button1')
  var leftButton = document.getElementById('left-button')
  var rightButton = document.getElementById('right-button')
  var move = document.getElementById('move')
  var box = document.getElementById('box')

  //获取最大移动距离
  // var max = box.offsetWidth - move.offsetWidth
  //获取move在box中x轴的偏移量
  // var x = move.offsetLeft
  // var interId, interId2
  // rightButton.onclick = function (e) {
  //   clearInterval(interId2)
  //   var left = move.offsetLeft
  //   interId = setInterval(function () {
  //     left += 15
  //     if (left > max) {
  //       left = max
  //       clearInterval(interId)
  //     }
  //     move.style.left = left + 'px'

  //   }, 20)
  // }
  // leftButton.onclick = function (e) {
  //   //清除向右的定时器
  //   clearInterval(interId)
  //   var left1 = move.offsetLeft
  //   interId2 = setInterval(function () {
  //     left1 -= 15
  //     if (left1 <= x) {
  //       left1 = x
  //       clearInterval(interId2)
  //     }
  //     move.style.left = left1 + 'px'
  //   }, 20)
  // }

  function levelMove(box, move) {
    var moveDistance = document.getElementById('distance').value
    console.log(moveDistance)
    var max = box.offsetWidth - move.offsetWidth
    var x = move.offsetLeft
    var left = move.offsetLeft
    var interId = setInterval(function () {
      left += moveDistance
      if (left > max) {
        left = max
        clearInterval(interId)
      } else if (left <= x) {
        left = x
        clearInterval(interId)
      }
      move.style.left = left + 'px'
    }, 20)
  }
  button1.onclick = levelMove(box, move)

</script>

</html>